$cid = 1;
var initPhotoSwipeFromDOM = function(gallerySelector) {

    // 解析来自DOM元素幻灯片数据（URL，标题，大小...）
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            linkEl,
            size,
            item,
            divEl;

        for(var i = 0; i < numNodes; i++) {

            figureEl = thumbElements[i]; // <figure> element

            // 仅包括元素节点
            if(figureEl.nodeType !== 1) {
                continue;
            }
            divEl = figureEl.children[0];
            linkEl = divEl.children[0]; // <a> element

            size = linkEl.getAttribute('data-size').split('X');

            // 创建幻灯片对象
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };



            if(figureEl.children.length > 1) {
                // <figcaption> content
                item.title = figureEl.children[1].innerHTML;
            }

            if(linkEl.children.length > 0) {
                // <img> 缩略图节点, 检索缩略图网址
                item.msrc = linkEl.children[0].getAttribute('src');
            }

            item.el = figureEl; // 保存链接元素 for getThumbBoundsFn
            items.push(item);
        }

        return items;
    };

    // 查找最近的父节点
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };

    // 当用户点击缩略图触发
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        // find root element of slide
        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        // find index of clicked item by looping through all child nodes
        // alternatively, you may define index via data- attribute
        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodeIndex = 0,
            index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) {
                continue;
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }



        if(index >= 0) {
            // open PhotoSwipe if valid index found
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };

    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
            params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');
            if(pair.length < 2) {
                continue;
            }
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        return params;
    };

    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;

        items = parseThumbnailElements(galleryElement);

        // 这里可以定义参数
        options = {
            barsSize: {
                top: 100,
                bottom: 100
            },
            fullscreenEl : false,
            shareButtons: [
                {id:'wechat', label:'分享微信', url:'#'},
                {id:'weibo', label:'新浪微博', url:'#'},
                {id:'download', label:'保存图片', url:'{{raw_image_url}}', download:true}
            ],

            // define gallery index (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
                // See Options -> getThumbBoundsFn section of documentation for more info
                var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect();

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }

        };

        // PhotoSwipe opened from URL
        if(fromURL) {
            if(options.galleryPIDs) {
                // parse real index when custom PIDs are used
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }

        // exit if index not found
        if( isNaN(options.index) ) {
            return;
        }

        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }

        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };

    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
};
function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}

var cname = '悦享';
var page1 = 1;
var page2 = 1;
(function(rf){
    var opt = {
        getDoms : function(){
            this.doms = {
                goTop : $('.goTop'),
                good : $('.good'),
                look : $('.look'),
                pinglun : $('.pinglun'),
                goodsparent : $('.goodsparent'),
                goodsparent1 : $('.goodsparent1'),
                index : 1,
                tab1: $('.tab1'),
                fabu: $('.titleIonc'),
                add_tw: $('#add_tw'),
                add_yx: $('#add_yx'),
            }
        },
        init : function (){
            var _self = this;
            _self.getDoms();
            _self.addEvent();
            _self.doms.add_tw.attr('href',WapSiteUrl+'/tmpl/discuss_add.html?type=2');
            _self.doms.add_yx.attr('href',WapSiteUrl+'/tmpl/discuss_add.html?type=1');
            var opt = {
                url : ApiUrl+"/index.php?act=circle&op=index&c_id=1",
                type: "GET",
            };
            rf.getData(opt,function(data){
                if (data['code']==200){
                    _self.template(_self.doms.goodsparent,data['datas'])
                    // execute above function
                    initPhotoSwipeFromDOM('.my-gallery');
                }
                if(data['datas']['code'] == 400){
                    window.location.href=WapSiteUrl+'/tmpl/member/login.html';
                }
            })
        },
        addEvent : function(){
            var _self = this;
            var _selfDoms = _self.doms;
            $(window).on('scroll',function(){
                console.log(111);
                var scrollTop = parseInt($(this).scrollTop());
                var scrollHeight = $(document).height();
                var windowHeight = $(this).height();
                if(scrollTop + windowHeight >= scrollHeight-1){
                    document.getElementsByClassName('list_loading')[0].style.display = 'block';
                    if($cid==1){
                       page = page1+1;
                    }
                    if($cid==2){
                       page = page2+1;
                    }
                    var opt = {
                        url : ApiUrl+"/index.php?act=circle&op=index&c_id="+$cid+"&page="+page,
                        type: "GET",
                    };
                    rf.getData(opt,function(data){
                        if (!isEmptyObject(data['datas'])) {
                            if (data['code'] == 200) {
                                if ($cid == 1) {
                                    _self.template(_self.doms.goodsparent, data['datas']);
                                    // execute above function
                                    initPhotoSwipeFromDOM('.my-gallery');
                                }
                                if ($cid == 2) {
                                    _self.template(_self.doms.goodsparent1, data['datas'])
                                    // execute above function
                                    initPhotoSwipeFromDOM('.my-gallery');
                                }
                            }
                        }else{
                            document.getElementsByClassName('list_loading')[0].style.display = 'none';
                            document.getElementsByClassName('nodata')[0].style.display = 'block';
                        }
                    })

                }
            });
            _selfDoms.fabu.on('click', function () {
                var key = getCookie('key');
                if(!key){
                    window.location.href = WapSiteUrl+'/tmpl/member/login.html';
                    return ;
                }
                $('.all').toggle()
            });
            _selfDoms.goTop.on('click',function(){
                $(document).scrollTop(0);
            });
            _selfDoms.good.on('click',function(){
                var opt = {
                    url : rf.interfaces.info
                };
//                    rf.getData(opt,function(data){
//                        _self.text()
//                    })
            })

            _selfDoms.look.on('click',function(){
                var opt = {
                    url : rf.interfaces.info
                };
//                    rf.getData(opt,function(data){
//                        _self.text()
//                    })
            })

            _selfDoms.pinglun.on('click',function(){
                var opt = {
                    url : rf.interfaces.info
                };
//                    rf.getData(opt,function(data){
//                        _self.text()
//                    })
            })
            _selfDoms.tab1.on('click',function(){
                if($(this).index()==0){
                    $('.main').fadeIn();
                    $('.main1').fadeOut();
                    $('.goodsparent').empty();
                    cname = "悦享";
                    _selfDoms.tab1.removeClass('active');
                    $(this).addClass('active');
                    var opt = {
                        url : ApiUrl+"/index.php?act=circle&op=index&c_id=1",
                        type: "GET",
                    };
                    $cid = 1;
                    rf.getData(opt,function(data){
                        if (data['code']==200){
                            _self.template(_self.doms.goodsparent,data['datas'])
                            // execute above function
                            initPhotoSwipeFromDOM('.my-gallery');
                        }
                    })
                }
                if($(this).index()==1){
                    $('.main1').fadeIn();
                    $('.main').fadeOut();
                    $('.goodsparent1').empty();
                    cname = "问答";
                    _selfDoms.tab1.removeClass('active');
                    $(this).addClass('active');
                    var opt = {
                        url : ApiUrl+"/index.php?act=circle&op=index&c_id=2",
                        type: "GET",
                    };
                    $cid = 2;
                    rf.getData(opt,function(data){
                        if (data['code']==200){
                            _self.template(_self.doms.goodsparent1,data['datas'])
                            // execute above function
                            initPhotoSwipeFromDOM('.my-gallery');
                        }
                    })
                }
            })
        },
        text : function(obj,number){
            obj.html(number)
        },
        template : function(obj,data){
            var text = '';
            console.log(data);
            for(var i=0;i<data.length;i++) {
                text += '<li class="goods_show">';
                text += "<a href='discuss_detail.html?cid="+$cid+"&t_id="+data[i]['theme_id']+"'><p style='font-size: 15px; padding-left:7px; margin-bottom: 6px; font-weight: 500;font-weight: 600;'><span style='color: #ff6666'>["+cname+"]</span>&nbsp;&nbsp;"+data[i]['theme_name']+"</p></a>"
                text += '<div class="top paddings">';
                text += '<div class="img">';
                 if (data[i]['avatar']==null) {
                    text += '<img src="'+SITEURL+'/data/upload/shop/common/default_user_portrait.gif?0.17620300 1484978714" alt="">';
                }else{
                    text += '<img src="'+SITEURL+data[i]["avator"]+'" />'
                }
                text += '</div>';
                text += '<div class="text">';
                text += '<p>'+data[i]["member_name"]+'</p>';
                text += '<p>'+data[i]["theme_addtime"]+'</p>';
                text += '</div>';
                text += '</div>';
                text += "<a href='discuss_detail.html?cid="+$cid+"&t_id="+data[i]['theme_id']+"'>"
                text += '<div class="textmiaoshu paddings">';

                text += '<p>'+data[i]["wap_content"]+'</p>';
                text += '</div>';
                text += '</a>';
                text += '<div class="my-gallery" data-pswp-uid="2">';
                if(data[i]["imags"][0]!=""){
                    for(var j=0;j<data[i]["imags"].length;j++){
                            text += '<figure><div class="thumb-img"><a href="'+SITEURL+'/data/upload/discuss/'+data[i]["imags"][j]+'" data-size="'+data[i]['imageSize'][j]+'"><img style="height:100%;" src="'+SITEURL+'/data/upload/discuss/'+data[i]["thumblist"][j]+'"></a></div></figure>';
                    }
                }
                text += '</div>';
                text += '<div class="list_footer">';
                text += '<div class="paddings">';
                text += '<p class="look">'+data[i]["theme_browsecount"]+'</p>';
                text += '<p class="good">'+data[i]["theme_commentcount"]+'</p>';
                text += '<p class="pinglun">'+data[i]["theme_likecount"]+'</p>';
                text += '</div>';
                text += '</div>';
                text += '</li>';
            }
            obj.append(text);
        }
    };

    opt.init();
})(window)

